<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12" :xs="0" />
      <el-col :span="12" :xs="24">
        <el-form
          class="login_form"
          :model="loginForm"
          :rules="rules"
          ref="loginForms"
        >
          <h1>HELLO</h1>
          <h2>欢迎来到蒋爷甄选</h2>
          <el-form-item prop="username">
            <el-input
              :prefix-icon="User"
              v-model="loginForm.username"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              show-password
              :prefix-icon="Lock"
              v-model="loginForm.password"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              :loading="loading"
              class="login_btn"
              type="primary"
              size="default"
              @click="login"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'
// 引入用户相关的小仓库
import useUserStore from '@/store/modules/user'
// 引入获取当前时间的函数
import { getTime } from '@/utils/time'

// 获取用户相关的小仓库
const userStore = useUserStore()
// 获取路由器
const $router = useRouter()
const $route = useRoute()
// 定义变量控制按钮加载效果
let loading = ref(false)

// 收集账号与密码数据
let loginForm = reactive({
  username: 'admin',
  password: '111111',
})

/*
 * 自定义校验规则所需要的函数
 * rule：就是校验规则对象，
 * value：就是表单元素的文本内容，
 * callback: 就是回调函数，符合条件触发 callback 放行通过，不符合条件触发 callback 注入错误信息
 */
const validatorUsername = (_rule: any, value: any, callback: any) => {
  if (value.length >= 2 && value.length <= 10) {
    callback()
  } else {
    callback(new Error('账号必须是2-10位'))
  }
}
const validatorPassword = (_rule: any, value: any, callback: any) => {
  if (value.length >= 6 && value.length <= 20) {
    callback()
  } else {
    callback(new Error('密码必须是6-20位'))
  }
}

// 定义表单数据的校验规则
const rules = {
  username: [
    // { required: true, message: '请输入账号', trigger: 'blur' },
    // { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
    // 自定义校验规则
    { trigger: 'blur', validator: validatorUsername },
  ],
  password: [
    // { required: true, message: '请输入密码', trigger: 'blur' },
    // { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
    { trigger: 'blur', validator: validatorPassword },
  ],
}
// 获取 el-form 表单
const loginForms = ref()

// 登录按钮回调
const login = async () => {
  // 确保全部的表单验证通过再发送请求
  await loginForms.value.validate()
  // 加载效果开始
  loading.value = true
  // 登录请求，将返回的 token 存储到 pinia 中
  try {
    // 保证登录成功
    await userStore.userLogin(loginForm)
    // 编程式导航跳转到首页
    // 判断登录的时候是否有 query 参数，有就往 query 参数跳转，没有就跳转到首页
    let redirect: any = $route.query.redirect
    await $router.push({ path: redirect || '/' })
    // 登录成功的提示信息
    ElNotification({
      type: 'success',
      title: `Hi，${getTime()}`,
      message: '登录成功，欢迎回来！',
      duration: 2000,
    })
  } catch (error) {
    // 登录失败的提示信息
    ElNotification({
      type: 'error',
      title: '登录失败',
      message: (error as Error).message,
    })
  } finally {
    // 加载效果结束
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.login_container {
  width: 100%;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover;

  .login_form {
    position: relative;
    width: 60%;
    top: 30vh;
    background: url('@/assets/images/login_form.png') no-repeat;
    background-size: cover;
    padding: 40px;

    h1 {
      color: white;
      font-size: 40px;
    }

    h2 {
      color: white;
      font-size: 20px;
      margin: 20px 0;
    }

    .login_btn {
      width: 100%;
      height: 40px;
    }
  }
}
</style>
